package com.yjt.fresh.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import com.yjt.fresh.R;
import com.yjt.fresh.adpater.AdpRvAtyProducts;
import com.yjt.fresh.adpater.AdpVpFrgCompanyVideos;
import com.yjt.fresh.api.ApiGetCompanyVideos;
import com.yjt.fresh.api.ApiGetHistoryVideoDeetail;
import com.yjt.fresh.api.ApiGetProducts;
import com.yjt.fresh.base.BaseSimpleActivity;
import com.yjt.fresh.bean.BeanHistory;
import com.yjt.fresh.bean.BeanProduct;
import com.yjt.fresh.bean.BeanVideoDetail;
import com.yjt.fresh.constant.MyConstants;
import com.yjt.fresh.fragment.FrgForCompanyVideos;
import com.yjt.fresh.utils.CommonsToolsHelper;
import com.yjt.fresh.widget.CustomToastResult;
import com.yjt.fresh.widget.GridSpacingItemDecoration;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import im.delight.android.webview.AdvancedWebView;

/**
 * Created by Administrator on 2018-08-21.
 */

public class AtyHistoryVideos extends BaseSimpleActivity {
    private static final int REQUEST_PERMISSION_CODE = 1008;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    @BindView(R.id.rlBack)
    RelativeLayout mRlBack;
    @BindView(R.id.tvAtyHistoryCompanyVideosTitle)
    TextView mTvTitle;
    @BindView(R.id.rvAppFrgHistoryCompanyVideos)
    RecyclerView mRv;
    @BindView(R.id.srlAppFrgHistoryCompanyVideos)
    SwipeRefreshLayout mSrl;
    @BindView(R.id.ivAtyHistoryCompanyVideosShare)
    ImageView mIvShare;
    private AdpRvAtyProducts mAdpProducts;
    private int mNextRequestPage = 1;
    private boolean isLoadMore;
    private ViewPager mVp;
    private AdvancedWebView mWebView;
    private String mVideoID;
    private ApiGetCompanyVideos mApiGetCompanyVideos;

    @Override
    protected int getContentView() {
        return R.layout.app_aty_history_company_videos;
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
    }

    @Override
    protected void initEvent() {
        initRv();
        initHead();
        getData();
        String content = getIntent().getStringExtra(MyConstants.CONTENT);
        String title = getIntent().getStringExtra(MyConstants.TITLE);
        mVideoID = getIntent().getStringExtra(MyConstants.VIDEO_ID);
        if (mVideoID != null){
            mIvShare.setVisibility(View.VISIBLE);
        }else {
            mIvShare.setVisibility(View.GONE);
        }
        refresh();
        mTvTitle.setText(title);

        initClick();

    }

    private void refresh() {
        boolean isWebView = getIntent().getBooleanExtra(MyConstants.IS_WEB_VIEW, false);
        if (isWebView){
            getWebViewData();
            mAdpProducts.setEnableLoadMore(false);
        }else {
            mWebView.setVisibility(View.GONE);
            getHotData();
        }
    }

    private void getWebViewData() {
        ApiGetHistoryVideoDeetail apiGetHistoryVideoDeetail = new ApiGetHistoryVideoDeetail(new HttpOnNextListener<BeanVideoDetail>() {
            @Override
            public void onNext(BeanVideoDetail beanVideoDetail) {
                setWebView(beanVideoDetail.getCONTENT());
                mAdpProducts.setNewData(beanVideoDetail.getList());
                mSrl.setRefreshing(false);
            }

            @Override
            public void onReLogin() {

            }
        },mContext,true,false,false);
        Map<String,Object> map = new HashMap<>();
        map.put("VIDEO_ID", mVideoID);
        apiGetHistoryVideoDeetail.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiGetHistoryVideoDeetail);
    }

    private void setWebView(String detail) {
        String content = detail;
        try {
            Document doc = Jsoup.parse(detail);
            Elements elements = doc.getElementsByTag("img");
            for (Element element : elements) {
                element.attr("width", "100%").attr("height", "auto");
            }

            content = doc.toString();
        } catch (Exception e) {
            content = detail;
        }
        mWebView.loadHtml(content);
    }

    private void initHead() {
        View head = View.inflate(mContext, R.layout.app_aty_history_company_videos_head, null);
        mVp = head.findViewById(R.id.vpAppFrgHistoryCompanyVideos);
        mWebView = head.findViewById(R.id.wbAppFrgHistoryCompanyVideos);
        mAdpProducts.setHeaderAndEmpty(true);
        mAdpProducts.addHeaderView(head);
        mAdpProducts.setEmptyView(R.layout.view_empty);
    }

    HttpOnNextListener<List<BeanProduct>> mProductsListener = new HttpOnNextListener<List<BeanProduct>>() {
        @Override
        public void onNext(List<BeanProduct> beanProducts) {
//            mAdpProducts.setEmptyView(R.layout.view_empty);
            if (isLoadMore) {
                setData(false, beanProducts);
            } else {
                setData(true, beanProducts);
                mSrl.setRefreshing(false);
            }
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };
    private void getHotData() {
        ApiGetProducts apiGetProducts = new ApiGetProducts(mProductsListener, mContext, true, false, false);
        Map<String, String> map = new HashMap<>();
        map.put("currentPage", mNextRequestPage+"");
        map.put("IS_INDEX", 1 + "");
        map.put("GOODSHOWPLACE", 1 + "");
        map.put("STORE_ID", getIntent().getStringExtra(MyConstants.USER_ID));
        apiGetProducts.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiGetProducts);
    }

    private void initClick() {
        mIvShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(mContext, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
                    } else {
                        share();
                    }
                } else {
                    share();
                }
            }
        });
        mRlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mSrl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mNextRequestPage = 1;
                isLoadMore = false;
                refresh();
            }
        });
        mAdpProducts.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                isLoadMore = true;
                refresh();
            }
        }, mRv);

        mAdpProducts.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(mContext,AtyProductDetail.class);
                intent.putExtra(MyConstants.GOODS_ID, mAdpProducts.getItem(position).getGOODS_ID());
                startActivity(intent);
            }
        });
    }

    private void getData() {
        mApiGetCompanyVideos = new ApiGetCompanyVideos(new HttpOnNextListener<List<BeanHistory>>() {
            @Override
            public void onNext(List<BeanHistory> beanHistories) {
                initVP(beanHistories);
            }

            @Override
            public void onReLogin() {

            }
        }, mContext, true, false, false);
        Map<String, Object> map = new HashMap<>();
        map.put("USER_ID", getIntent().getStringExtra(MyConstants.USER_ID));
        mApiGetCompanyVideos.setMap(map);
        HttpManager.getInstance().doHttpDeal(mApiGetCompanyVideos);
    }

    private void initRv() {
        GridLayoutManager layoutManager = new GridLayoutManager(mContext, 2);
        List<BeanProduct> list = new ArrayList<>();
        mRv.setLayoutManager(layoutManager);
        mAdpProducts = new AdpRvAtyProducts(R.layout.app_recycle_item_products, list);
        mRv.addItemDecoration(new GridSpacingItemDecoration(2, CommonsToolsHelper.dip2px(mContext, 5), true));
        mRv.setAdapter(mAdpProducts);
        mAdpProducts.bindToRecyclerView(mRv);
    }
    private void setData(boolean isRefresh, List<BeanProduct> data) {
        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdpProducts.setNewData(data);
        } else {
            if (size > 0) {
                mAdpProducts.addData(data);
                mAdpProducts.loadMoreComplete();
            }else {
                mAdpProducts.loadMoreEnd(false);
            }
        }
    }
    private void initVP(List<BeanHistory> beanHistories) {
        ArrayList<FrgForCompanyVideos> frgVideos = new ArrayList<>();
        if (beanHistories != null && beanHistories.size() > 0) {
            for (int i = 0; i < beanHistories.size(); i++) {
                FrgForCompanyVideos frgVideo = new FrgForCompanyVideos();
                Bundle bundle = new Bundle();
                bundle.putSerializable(MyConstants.VIDEO_OBJ, beanHistories.get(i));
                frgVideo.setArguments(bundle);
                frgVideos.add(frgVideo);
            }
        }
        AdpVpFrgCompanyVideos adpVpFrgHistoryVideo = new AdpVpFrgCompanyVideos(getSupportFragmentManager(), frgVideos);
        mVp.setAdapter(adpVpFrgHistoryVideo);

        mVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                GSYVideoManager.onPause();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        GSYVideoManager.onPause();
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                Log.i("MainActivity", "申请的权限为：" + permissions[i] + ",申请结果：" + grantResults[i]);
            }
        }
    }

    private void share() {
        UMWeb umWeb = new UMWeb(mApiGetCompanyVideos.getBaseUrl()+"app/videos/detail?VIDEO_ID="+mVideoID);
        UMImage umImage = new UMImage(mContext, R.mipmap.ic_launcher);
        umWeb.setTitle("健康肉");
        umWeb.setDescription(mTvTitle.getText().toString());
        umWeb.setThumb(umImage);
        new ShareAction(mContext)
                .withMedia(umWeb)
                .setDisplayList(SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                .setCallback(new UMShareListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media) {

                    }

                    @Override
                    public void onResult(SHARE_MEDIA share_media) {
                        CustomToastResult.show("分享成功");
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, Throwable throwable) {

                        Toast.makeText(mContext, throwable.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media) {

                        Toast.makeText(mContext, "分享取消", Toast.LENGTH_SHORT).show();
                    }
                }).open();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(mContext).onActivityResult(requestCode, resultCode, data);
    }
}
